package eu.news.interconnect.server;

import java.net.InetAddress;
import java.net.UnknownHostException;

import eu.news.config.Debugger;
import eu.news.data.pojo.Interface;
import eu.news.interconnect.Message;

/**
 * 接口身份验证器
 * @author WZZ
 *
 */
public class Authenticator {
	
	public static final int SUCCESS = 0;
	
	public static final int ERROR_NO_POWER = 1;
	
	public static final int ERROR_NOT_FOUND = 2;
	
	public static final int ERROR_AUTH_FAIL = 3;

	public static int check(Message message,String ip){
		Interface face = InterfaceMap.getByAccessKey(message.getAccessKey());
		if(face == null)
			return ERROR_NOT_FOUND;
		try {
			InetAddress address = InetAddress.getByName(face.getBindIpOrDomain());
			if (!address.getHostAddress().equals(ip))
				return ERROR_AUTH_FAIL;
			if ((face.getPower()&message.getType()) > 0||message.getType() <= 0){
				//权限检验或者Message是一个信息包
				return SUCCESS;
			}
			return ERROR_AUTH_FAIL;
		} catch (UnknownHostException e) {
			Debugger.printStackTrace(e);
			return ERROR_AUTH_FAIL;
		}
	}
}
